package com.tiyende.credit.loop.ui.activity

import android.annotation.SuppressLint
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.GravityCompat
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lib.common.adapter.CommonOnItemChildClickListener
import com.lib.common.adapter.CommonRecyclerViewAdapter
import com.lib.common.adapter.CommonViewHolderHelper
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.base.BaseFragment
import com.tiyende.credit.loop.base.app.TiyendeActivityStackManager
import com.tiyende.credit.loop.common.CommonActivity
import com.tiyende.credit.loop.databinding.TiyendeActivityMainBinding
import com.tiyende.credit.loop.event.TiyendeEventData
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.ui.contract.IViewContract
import com.tiyende.credit.loop.ui.dialog.TiyendeVersionDialog
import com.tiyende.credit.loop.ui.fragment.TiyendeUserCenterFragment
import com.tiyende.credit.loop.ui.presenter.TiyendeMainPresenter
import com.tiyende.credit.loop.utils.TiyendeDateUtil
import com.tiyende.credit.loop.utils.TiyendeTitleBarUtil
import com.tiyende.credit.loop.utils.helper.TiyendeConfigsHelper
import com.tiyende.credit.loop.utils.helper.TiyendeCreditStatusHelper
import com.tiyende.credit.loop.utils.helper.TiyendeProcessHelper
import com.tiyende.credit.loop.utils.helper.TiyendeVersionHelper
import com.tiyende.credit.loop.utils.log.TiyendeLogger
import com.tiyende.credit.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedKey
import org.json.JSONObject
import java.util.TimeZone

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/28 14:39
 * @Annotation：主页
 */
class TiyendeMainActivity: CommonActivity(), IViewContract.ITiyendeMainView {
    lateinit var binding: TiyendeActivityMainBinding
    var presenter: TiyendeMainPresenter? = null
    private var tabAdapter: TiyendeMainTabAdapter? = null

    private var fragmentManager: FragmentManager? = null
    private var curtFragment: BaseFragment? = null
    var eventRemark = ""

    //个人中心
    var userCenterFragment: TiyendeUserCenterFragment? = null
    private var versionHelper: TiyendeVersionHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            //更新成功
        } else {

        }
    }

    override fun getTiyendeRootView(): View {
        binding = TiyendeActivityMainBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        binding.mainParentLayout.setPadding(0,TiyendeTitleBarUtil.getStatusBarHeight(),0,0)
        setBackExit(true)

        addTiyendeUserMenuFragment()
        initTiyendeTabGridView()
    }

    override fun initTiyendeListener() {
        binding.mainUserImageView.setOnClickListener {
            val isOpen = binding.mainDrawerLayout.isDrawerOpen(GravityCompat.START)
            if (isOpen){//是否打开
                binding.mainDrawerLayout.closeDrawer(GravityCompat.START,true)
                addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_CENTER,"$eventRemark Close")
            } else {
                binding.mainDrawerLayout.openDrawer(GravityCompat.START,true)
                addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_CENTER,"$eventRemark Open")
            }
        }
        binding.mainCustomerImageView.setOnClickListener {
            showCustomerDialog(eventRemark)
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,eventRemark)
        }
    }

    override fun loadTiyendeData() {
        //保存时区id 用于判断是否切换时区
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_TIMEZONE_ID, TimeZone.getDefault().id)
        if (presenter == null){
            presenter = TiyendeMainPresenter(this)
        }
        showTiyendeLoading()
        presenter?.queryTiyendeMainTabList()
        presenter?.queryTiyendeMainFragmentList()
        presenter?.queryTiyendeProcessAction()
        presenter?.queryTiyendeOrderListAction()
    }

    override fun onResume() {
        super.onResume()
        versionHelper?.resume()
    }

    /**
     * 初始化Tab列表
     */
    private fun initTiyendeTabGridView() {
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.mainTabListView.layoutManager = layoutManager
        tabAdapter = TiyendeMainTabAdapter(binding.mainTabListView)
        binding.mainTabListView.adapter = tabAdapter
        binding.mainTabListView.itemAnimator = DefaultItemAnimator()
        tabAdapter?.setOnItemChildClickListener(CommonOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.mainTabItemLayout) {//切换item
//                binding.mainViewPager.currentItem = position
                presenter?.setMainCurrentItemIndex(position)
            }
        })
    }

    override fun showTiyendeMainList(tabList: ArrayList<JSONObject>) {
        tabAdapter?.data = tabList
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun notifyTiyendeMainDataChanged(curtIndex: Int) {
        tabAdapter?.notifyDataSetChanged()
        eventRemark = if (curtIndex == 0){
            "Home Page"
        } else {
            "Repay Page"
        }
    }

    /**
     * 使用show() hide()切换页面
     * 显示fragment
     */
    override fun showTiyendeMainFragment(fragment: BaseFragment, index: Int) {
        //设置状态栏文字颜色
        if (fragmentManager == null) {
            fragmentManager = supportFragmentManager
        }
        val transaction = fragmentManager?.beginTransaction()
        curtFragment?.let {
            transaction?.hide(it)
        }

        //如果之前没有添加过
        if (!fragment.isAdded) {
            //第三个参数为添加当前的fragment时绑定一个tag
            transaction?.add(R.id.mainContainerLayout, fragment, fragment.javaClass.canonicalName)
        } else {
            transaction?.show(fragment)
        }
        curtFragment = fragment
        transaction?.commitAllowingStateLoss()
    }

    /**
     * 需要校验手机号
     */
    override fun showTiyendeMainMustCheckMobilePage() {
        //授信是否被拒绝
        val creditStatus = TiyendeProcessHelper.queryTiyendeAuthenticationBeforeRiskStatus()
        val isCreditRejected = TiyendeCreditStatusHelper.TiyendeCreditStatusRepository().isCreditRejected(creditStatus)
        if (isCreditRejected){
            return
        }
        //当前栈顶是 手机号校验页面 不重复跳转
        if (TiyendeActivityStackManager.isCurrentActivity(TiyendeCheckMobileActivity::class.java)){
            return
        }
        //是否是审核账号
        val isAdmin = TiyendeSharedHelper.queryTiyendeSharedBoolean(TiyendeSharedKey.TIYENDE_IS_CONFIG_ACCOUNT)
        if(isAdmin) {//审核账号，直接不走校验
            return
        }
        TiyendeCheckMobileActivity.start(this)
    }

    /**
     * 版本更新Dialog
     */
    private fun showTiyendeMainVersionUpdateDialog() {
        val lastShowTime = TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_UPDATE_LAST_TIME)
        if (lastShowTime.isNotEmpty() && TiyendeDateUtil.isSameDay(lastShowTime.toLong(),System.currentTimeMillis())){
            return
        }
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_UPDATE_LAST_TIME,"${System.currentTimeMillis()}")
        val updateDialog = TiyendeVersionDialog(this,"Home page",object : TiyendeVersionDialog.IDialogCallback{
            override fun onClick(view: View?) {
                try {
                    if (versionHelper == null){
                        versionHelper = TiyendeVersionHelper(activity = this@TiyendeMainActivity, isMust = true, updateLauncher)
                    }
                    versionHelper?.startVersionUpdate {  }
                } catch (e: Exception) {
                    showTiyendeToast(getString(R.string.tiyende_update_no_new_version))
                }
            }
        })
        updateDialog.show()
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        TiyendeLogger.e(">>>>>>>>>>main>>>>>>>>>>>sub event："+event.eventType)
        when(event.eventType){
            TiyendeEventData.TYPE.TIYENDE_CREDIT_REFRESH -> {//刷新授信状态
                presenter?.queryTiyendeCreditStatusAction()
            }
            TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESH -> {//刷新流程
                presenter?.queryTiyendeProcessAction()
            }
            TiyendeEventData.TYPE.TIYENDE_ORDER_REFRESH -> {//刷新订单列表
                presenter?.queryTiyendeOrderListAction()
            }
            TiyendeEventData.TYPE.TIYENDE_SHOW_HOME -> {//显示首页
                presenter?.setMainCurrentItemIndex(0)
            }
            TiyendeEventData.TYPE.TIYENDE_SHOW_REPAY -> {//待还款
                presenter?.setMainCurrentItemIndex(1)
            }
            TiyendeEventData.TYPE.TIYENDE_SHOW_HOME_UPDATE -> {//更新通知
                //是否有新版本
                val isNewVersion = TiyendeConfigsHelper.isTiyendeUpdate()
                if (isNewVersion){
                    showTiyendeMainVersionUpdateDialog()
                }
            }
            else -> {

            }
        }
    }

    /**
     * 添加侧边菜单
     */
    @SuppressLint("CommitTransaction")
    private fun addTiyendeUserMenuFragment(){
        if (userCenterFragment == null){
            userCenterFragment = TiyendeUserCenterFragment(binding.mainDrawerLayout)
        }
        userCenterFragment?.let {
            if (!it.isAdded){
                supportFragmentManager
                    .beginTransaction()
                    .replace(R.id.mainMenuLayout, it) // 此处的R.id.fragment_container是要盛放fragment的父容器
                    .commitAllowingStateLoss()
            }
        }
    }

    class TiyendeMainTabAdapter(recyclerView: RecyclerView?) : CommonRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.tiyende_activity_main_item) {
        override fun setItemChildListener(helper: CommonViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.mainTabItemLayout)
        }
        override fun fillData(helper: CommonViewHolderHelper, position: Int, model: JSONObject) {
            val mainTabImageView = helper.getImageView(R.id.mainTabImageView)
            val txtMainTabTitle = helper.getTextView(R.id.txtMainTabTitle)
            txtMainTabTitle.text = model.optString("tabTitle")
            mainTabImageView.setImageResource(model.optInt("tabIcon"))

            when(model.optBoolean("isSelect", false)){
                true -> {
                    txtMainTabTitle.visibility = View.VISIBLE
                    mainTabImageView.visibility = View.INVISIBLE
                    helper.setVisibility(R.id.mainTabPointView,View.VISIBLE)
                }
                else -> {
                    txtMainTabTitle.visibility = View.INVISIBLE
                    mainTabImageView.visibility = View.VISIBLE
                    helper.setVisibility(R.id.mainTabPointView,View.INVISIBLE)
                }
            }
        }
    }
}